package com.bt.lms.ui.action.teacher.basic.info;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.TeacherBizTypeConstant;
import com.bt.lms.entity.TeacherBasicInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.ui.page.common.action.pageteaching.TeacherLabAction;
import com.bt.lms.ui.page.info.PageAddTeacherBasicInfo;
import com.bt.lms.ui.page.info.PageTeacherBasicInfo;
import com.bt.lms.ui.page.info.Vo.AddTeacherBasicInfoVo;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 新增教师保存按钮事件
 */
public class AddTeacherBasicInfoSaveBtnAction implements EventHandler {

    private String errors;

    private PageAddTeacherBasicInfo addTeacher;
    public AddTeacherBasicInfoSaveBtnAction(PageAddTeacherBasicInfo pageAddTeacherBasicInfo) {
        this.addTeacher = pageAddTeacherBasicInfo;
    }

    @Override
    public void handle(Event event) {

        //1、获取用户输入
        AddTeacherBasicInfoVo addTeacherBasicInfoVo = getInParams();
        //2、验证用户输入
        String validateMsg = validateInParam(addTeacherBasicInfoVo);
        //3、组包
        byte[] msgByte = null;
        if (validateMsg.equals("")){
            //验证通过
            msgByte = handle2ReqMsgPacket(addTeacherBasicInfoVo);
        }else {
            //提示，程序终止
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(errors);
            alert.show();
            return;
        }
        //4、组网
        Socket socket = getNet();
        //5、发消息
        boolean flag = sendReqMsgPacket(socket,msgByte);

        if (flag){
            PageTeacherBasicInfo pageTeacherBasicInfo = new PageTeacherBasicInfo();
            Integer index = TeacherLabAction.pageSkipInfo.getIndex();
            Pane pane = TeacherLabAction.pageSkipInfo.getPane();
            pane.getChildren().set(index,pageTeacherBasicInfo);


        }




    }

    /**
     * 5、发送消息
     * @param socket
     * @param msgByte
     * @return
     */
    private boolean sendReqMsgPacket(Socket socket,byte[] msgByte){

        try {
            OutputStream out = socket.getOutputStream();
            out.write(msgByte);
            out.flush();

            byte[] buffer = new byte[1024];
            InputStream in = socket.getInputStream();
            in.read(buffer);
            in.close();

            out.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    /**
     * 4、组网
     * @return
     */
    private Socket getNet() {
        String ip = "127.0.0.1";
        int port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return socket;
    }


    /**
     * 3、组包
     * @param addTeacherBasicInfoVo  vo
     * @return  数组
     */
    private byte[] handle2ReqMsgPacket(AddTeacherBasicInfoVo addTeacherBasicInfoVo) {

        TeacherBasicInfo teacherBasicInfo = new TeacherBasicInfo();
        String data = null;
        try {
            BeanUtils.copyProperties(teacherBasicInfo,addTeacherBasicInfoVo);
            data = JSON.toJSONString(teacherBasicInfo);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        ReqMsg reqMsg = new ReqMsg();//请求消息
        reqMsg.setBizType(TeacherBizTypeConstant.TEACHER_ADD);
        reqMsg.setData(data);
        byte[] msgByte = reqMsg.toBytes();
        return msgByte;
    }

    /**
     * 验证用户输入
     * @param addTeacherBasicInfoVo vo
     * @return  错误信息
     */
    private String validateInParam(AddTeacherBasicInfoVo addTeacherBasicInfoVo) {


        errors = "";


        //账号
        String account = addTeacherBasicInfoVo.getAccount();
        int accountTFLength = account.length();
        if (account.equals("")){
            errors += " 账号不能为空"+"\r\n";
        }else if (accountTFLength>32){
            errors += " 账号过长，最多可填写32个字（包括中文，英语，数字，符号）"+"\r\n";
        }

        //姓名
        String nameStr = addTeacherBasicInfoVo.getName();
        int nameTFLength = nameStr.length();
        if (nameStr.equals("")){
            errors +=  " 姓名不能为空"+"\r\n";
        }else if (nameTFLength>32){
            errors +=  " 请输入正确的姓名"+"\r\n";
        }

        //证件类型
        Integer certificateType = addTeacherBasicInfoVo.getCertificateType();
        //证件号码
        String certificateNumber = addTeacherBasicInfoVo.getCertificateNumber();
        int numberLength = certificateNumber.length();
        if (certificateType==1){
            if (certificateNumber.equals("")){
                errors += "证件号码不能为空"+"\r\n";
            }else if (numberLength>18||numberLength<18){
                errors += "请输入正确的身份证号"+"\r\n";
            }
        }else if (certificateType==2){
            if (certificateNumber.equals("")){
                errors += "证件号码不能为空"+"\r\n";
            }else if (numberLength>9||numberLength<9){
                errors += "请输入正确的护照证号"+"\r\n";
            }
        }

        //出生日期
        LocalDate birthdate = addTeacherBasicInfoVo.getBirthdate();
        int datePickerValueYear = birthdate.getYear();
        LocalDateTime localDateTime = LocalDateTime.now();
        int localDateTimeYear = localDateTime.getYear();
        if (birthdate==null){
            errors +=  " 请输入出生日期"+"\r\n";
        }else if (datePickerValueYear>=localDateTimeYear||localDateTimeYear-datePickerValueYear>150){
            errors +=  " 请输入正确的出生日期"+"\r\n";
        }



        //籍贯
        String birthplace = addTeacherBasicInfoVo.getBirthplace();
        int birthplaceTFLength = birthplace.length();
        if (birthplace.equals("")){
            errors +=  " 籍贯不能为空"+"\r\n";
        }else if (birthplaceTFLength>32){
            errors +=  " 籍贯过长，最多可填写32个字（包括中文，英语，数字，符号）"+"\r\n";

        }

        //民族
        String nation = addTeacherBasicInfoVo.getNation();
        int nationTFLength = nation.length();
        if (nation.equals("")){
            errors +=  " 民族不能为空"+"\r\n";
        }else if (nationTFLength>32){
            errors += " 请输入正确的民族"+"\r\n";
        }

        //专业
        String specialty = addTeacherBasicInfoVo.getSpecialty();
        int specialtyTfLength = specialty.length();
        if (specialty.equals("")){
            errors +=  " 专业不能为空"+"\r\n";
        }else if (specialtyTfLength>32){
            errors +=  " 专业过长，最多可填写32个字（包括中文，英语，数字，符号）"+"\r\n";
        }

        //职称
        String jobTitle = addTeacherBasicInfoVo.getJobTitle();
        int jobTitleLength = jobTitle.length();
        if (jobTitle.equals("")){
            errors +=  " 职称不能为空"+"\r\n";

        }else if (jobTitleLength>32){
            errors +=  " 职称过长，最多可填写32个字（包括中文，英语，数字，符号）"+"\r\n";

        }

        //教龄
        String teachingAge = addTeacherBasicInfoVo.getTeachingAge();
        if (!teachingAge.equals("")){
            try {
                int parseInt = Integer.parseInt(teachingAge);
            } catch (NumberFormatException e) {
                errors += "请填写数字" + "\r\n";
            }
        }else {
            errors += "教龄不能为空" + "\r\n";
        }


        //移动电话
        String phone = addTeacherBasicInfoVo.getPhone();
        int phoneLength = phone.length();
        if (phone.equals("")){
            errors +=  " 移动电话不能为空"+"\r\n";

        }else if (phoneLength>11&&phoneLength<11){
            errors += " 请输入正确的手机号"+"\r\n";
        }


        //备注
        String researchInterests = addTeacherBasicInfoVo.getResearchInterests();
        int outcomeTALength = researchInterests.length();
        if (outcomeTALength>400){
            errors +=  " 备注最多可填400个字（包含中文，英语，数字，符号）"+"\r\n";
        }

        return errors;
    }


    /**
     * 获取用户输入
     * @return
     */
    public AddTeacherBasicInfoVo getInParams(){


        TextField accountTF = (TextField) addTeacher.lookup("#accountTF");//账号
        ComboBox certificateCB = (ComboBox) addTeacher.lookup("#certificateCB");//证件类型
        ComboBox genderComboBox = (ComboBox) addTeacher.lookup("#genderComboBox");//性别
        TextField birthplaceTF = (TextField) addTeacher.lookup("#birthplaceTF");//籍贯
        ComboBox politicsStatusCom = (ComboBox) addTeacher.lookup("#politicsStatusCom");//政治面貌
        TextField specialtyTf = (TextField) addTeacher.lookup("#specialtyTF");//专业
        ComboBox highestDegreeCom = (ComboBox) addTeacher.lookup("#highestDegreeCom");//最高学历
        TextField phoneTf = (TextField) addTeacher.lookup("#phoneTF");//移动电话
        TextField nameTF = (TextField) addTeacher.lookup("#nameTF");//姓名
        TextField certificateNumberTF = (TextField) addTeacher.lookup("#certificateNumberTF"); //证件号码
        DatePicker birthdateDP = (DatePicker) addTeacher.lookup("#birthdateDP");//出生日期
        TextField nationTF = (TextField) addTeacher.lookup("#nationTF");//民族
        ComboBox unitCom = (ComboBox) addTeacher.lookup("#unitCom");//所属单位
        TextField rankTF = (TextField) addTeacher.lookup("#rankTF");//职称
        TextField seniorityTF = (TextField) addTeacher.lookup("#seniorityTF");//教龄
        TextArea remarkTA = (TextArea) addTeacher.lookup("#remarkTA");//研究方向及成果

        AddTeacherBasicInfoVo addTeacherBasicInfoVo = new AddTeacherBasicInfoVo();

        LocalDate birthdateDPValue = birthdateDP.getValue();
        addTeacherBasicInfoVo.setBirthdate(birthdateDPValue);//生日

        String nation = nationTF.getText().trim();
        addTeacherBasicInfoVo.setNation(nation);


        String accountStr = accountTF.getText().trim();
        addTeacherBasicInfoVo.setAccount(accountStr);//账号

        String certificateCBValue = (String) certificateCB.getValue();//证件类型
        Integer certificateValue = -1;
        switch (certificateCBValue){
            case "身份证":
                certificateValue = 1;
                break;
            case "护照":
                certificateValue = 2;
                break;
        }
        addTeacherBasicInfoVo.setCertificateType(certificateValue);

        String genderComboBoxValue = (String) genderComboBox.getValue();//性别
        Integer genderCBValue = -1;
        switch (genderComboBoxValue){
            case "男":
                genderCBValue = 1;
                break;
            case "女":
                genderCBValue = 2;
                break;
        }
        addTeacherBasicInfoVo.setGender(genderCBValue);

        String birthplaceStr = birthplaceTF.getText().trim();//籍贯
        addTeacherBasicInfoVo.setBirthplace(birthplaceStr);

        String politicsStatusComValue = (String) politicsStatusCom.getValue();//政治面貌
        Integer politicsSCB = -1;
        switch (politicsStatusComValue){
            case "群众":
                politicsSCB = 1;
                break;
            case "党员":
                politicsSCB = 2;
                break;
            case "团员":
                politicsSCB = 3;
                break;
        }
        addTeacherBasicInfoVo.setPoliticsStatus(politicsSCB);

        String specialtyStr = specialtyTf.getText().trim();//专业
        addTeacherBasicInfoVo.setSpecialty(specialtyStr);

        String highestDegreeComValue = (String) highestDegreeCom.getValue();//最高学历
        Integer highestDegreeCBValue = -1;
        switch (highestDegreeComValue){
            case "博士":
                highestDegreeCBValue = 1;
                break;
            case "硕士":
                highestDegreeCBValue = 2;
                break;
            case "本科":
                highestDegreeCBValue = 3;
                break;
            case "荣誉博士":
                highestDegreeCBValue = 4;
                break;
        }
        addTeacherBasicInfoVo.setHighestDegree(highestDegreeCBValue);

        String phoneStr = phoneTf.getText().trim();//移动电话
        addTeacherBasicInfoVo.setPhone(phoneStr);

        String nameStr = nameTF.getText().trim();//姓名
        addTeacherBasicInfoVo.setName(nameStr);

        String certificateNumberStr = certificateNumberTF.getText().trim();//证件号码
        addTeacherBasicInfoVo.setCertificateNumber(certificateNumberStr);

//        String nationCBValue = (String) nationCB.getValue();//民族
//        addTeacherBasicInfoVo.setNation(nationCBValue);

        String unitComValue = (String) unitCom.getValue();//所属学习中心
        Integer unitValue = -1;
        switch (unitComValue){
            case "北京大学":
                unitValue = 1;
                break;
            case "北京师范大学":
                unitValue = 2;
                break;
        }
        addTeacherBasicInfoVo.setLearningCenter(unitValue);

        String rankStr = rankTF.getText().trim();//职称
        addTeacherBasicInfoVo.setJobTitle(rankStr);

        String seniorityStr = seniorityTF.getText().trim();//教龄
        addTeacherBasicInfoVo.setTeachingAge(seniorityStr);

        String remarkStr = remarkTA.getText().trim();//备注
        addTeacherBasicInfoVo.setResearchInterests(remarkStr);

        return addTeacherBasicInfoVo;
    }


}




















